package com.qf.flash.ui.chat;

import android.app.Activity;
import android.content.Context;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.hyphenate.chat.EMClient;
import com.mcxtzhang.swipemenulib.SwipeMenuLayout;
import com.qf.dblib.dao.entity.ChatUserBean;
import com.qf.dblib.dao.entity.InviteMessage;
import com.qf.flash.R;
import com.qf.flash.utils.ImageLoader;
import com.qf.flashlib.adapter.BaseRViewItem;
import com.qf.flashlib.adapter.RViewHolder;
import com.qf.flashlib.widget.CustomProgressDialog;

import org.litepal.LitePal;

import java.util.List;

import static com.qf.flash.constant.Constants.AGREED;
import static com.qf.flash.constant.Constants.BEAPPLYED;
import static com.qf.flash.constant.Constants.BEINVITEED;
import static com.qf.flash.constant.Constants.GROUPINVITATION;
import static com.qf.flash.constant.Constants.REFUSED;

public class NewFriendsItem extends BaseRViewItem<Object> {
    private TextView accept;
    private ChatUserBean chatUserBean;

    @Override
    public boolean isItemView(Object entity, int position) {
        return entity instanceof ChatUserBean;
    }

    @Override
    public int getItemLayout() {
        return R.layout.item_new_frineds;
    }

    @Override
    public void convert(RViewHolder holder, Object entity, int position, int itemSize) {

        chatUserBean = (ChatUserBean) entity;
        Button btn = holder.getView(R.id.btnDelete);
        SwipeMenuLayout mSwipeMenuLayout = holder.getView(R.id.swipeMenuLayout);
        ImageView ivHead = holder.getView(R.id.iv_head);
        accept = holder.getView(R.id.tv_accept);
        ImageLoader.loadCircleHead(holder.getmConvertView().getContext(), chatUserBean.getPhoto(), ivHead);
        holder.setText(R.id.name, chatUserBean.getName());
        holder.setText(R.id.tv_level, "LV." + chatUserBean.getLevel());
        if (chatUserBean.getSex().equals("1")) {
            holder.setImageResource(R.id.iv_sex, R.mipmap.icon_man);
        } else {
            holder.setImageResource(R.id.iv_sex, R.mipmap.icon_woman);
        }

        accept.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                List<InviteMessage> inviteMessages = LitePal.where("from=?", chatUserBean.getUid()).find(InviteMessage.class);
                if (inviteMessages.size() == 1) {
                    InviteMessage inviteMessage = inviteMessages.get(0);
                    acceptInvitation(position,accept, inviteMessage, mSwipeMenuLayout, holder.getmConvertView().getContext());
                }

            }
        });
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mSwipeMenuLayout.smoothClose();

                List<InviteMessage> inviteMessages = LitePal.where("from=?", chatUserBean.getUid()).find(InviteMessage.class);
                if (inviteMessages.size() == 1) {
                    InviteMessage inviteMessage = inviteMessages.get(0);
                    refuseInvitation(position,inviteMessage, holder.getmConvertView().getContext(),mSwipeMenuLayout);
                }
            }
        });
    }

    // 接受好友验证
    private void acceptInvitation(int position,final TextView tvAgree, final InviteMessage msg, SwipeMenuLayout mSwipeMenuLayout, Context context) {
        CustomProgressDialog dialog = new CustomProgressDialog(context);
        dialog.setTipText("正在添加……");
        dialog.show();
        final String str2 = context.getResources().getString(R.string.Has_agreed_to);
        final String str3 = context.getResources().getString(R.string.Agree_with_failure);


        new Thread(new Runnable() {
            public void run() {
                // call api
                try {
                    if (msg.getStatus() == BEINVITEED) {//accept be friends
                        EMClient.getInstance().contactManager().acceptInvitation(msg.getFrom());
                    } else if (msg.getStatus() == BEAPPLYED) { //accept application to join group
                        EMClient.getInstance().groupManager().acceptApplication(msg.getFrom(), msg.getGroupId());
                    } else if (msg.getStatus() == GROUPINVITATION) {
                        EMClient.getInstance().groupManager().acceptInvitation(msg.getGroupId(), msg.getGroupInviter());
                    }
                    msg.setStatus(AGREED);
                    msg.save();
                    // update database
                    ((Activity) context).runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            chatUserBean.save();
                            tvAgree.setText(str2);
                            tvAgree.setBackground(null);
                            tvAgree.setEnabled(false);
                            dialog.dismiss();
                            reMovedOneMsg.deleteOne(position);
                            reMovedOneMsg.addOne(chatUserBean.getUid());
                        }
                    });
                } catch (final Exception e) {
                    ((Activity) context).runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            dialog.dismiss();
                            Toast.makeText(context, str3 + e.getMessage(), Toast.LENGTH_LONG).show();
                        }
                    });

                }
            }
        }).start();
    }

    // 拒绝好友验证
    private void refuseInvitation(int position, final InviteMessage msg, Context context, SwipeMenuLayout mSwipeMenuLayout) {
        CustomProgressDialog dialog = new CustomProgressDialog(context);
        dialog.setTipText("正在拒绝……");
        dialog.show();

        new Thread(new Runnable() {
            public void run() {
                // call api
                try {
                    if (msg.getStatus() == BEINVITEED) {//decline the invitation
                        EMClient.getInstance().contactManager().declineInvitation(msg.getFrom());
                    } else if (msg.getStatus() == BEAPPLYED) { //decline application to join group
                        EMClient.getInstance().groupManager().declineApplication(msg.getFrom(), msg.getGroupId(), "");
                    } else if (msg.getStatus() == GROUPINVITATION) {
                        EMClient.getInstance().groupManager().declineInvitation(msg.getGroupId(), msg.getGroupInviter(), "");
                    }
                    msg.setStatus(REFUSED);
                    // update database
                    msg.save();
                    ((Activity) context).runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            dialog.dismiss();

                            mSwipeMenuLayout.setEnabled(false);
                            reMovedOneMsg.deleteOne(position);
                        }
                    });
                } catch (final Exception e) {
                    ((Activity) context).runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            dialog.dismiss();
                            Toast.makeText(context, "拒绝失败:" + e.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    });

                }
            }
        }).start();
    }

    private ReMovedOneMsg reMovedOneMsg;

    public void setReMovedOneMsg(ReMovedOneMsg reMovedOneMsg){
        this.reMovedOneMsg = reMovedOneMsg;
    }
    public interface ReMovedOneMsg{
        void deleteOne(int position);
        void addOne(String uid);
    }
}
